import { ComponentType, RenderComponent } from './RenderComponent'
import { DragScaleComponent } from './DragScaleComponent'
import SealSvg from "~/assets/seal.svg?raw";

let IMAGE:HTMLImageElement| null = null;
function loadImage() {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    if (IMAGE !== null) {
      resolve(IMAGE);
      return
    };
    IMAGE = new Image();
    IMAGE.src = 'data:image/svg+xml;base64,' + window.btoa(SealSvg);
    IMAGE.onload = () => {
      resolve(IMAGE!);
    };
    IMAGE.onerror = (error) => {
      reject(error);
    };
  });
}

// seal 默认尺寸
const SEAL_DEFAULT_WIDTH = 151;
const SEAL_DEFAULT_HEIGHT = 151;

export class SealComponent extends RenderComponent {
  constructor(
    _startX: number,
    _startY: number,
    _endX: number = _startX + SEAL_DEFAULT_WIDTH,
    _endY: number = _startY + SEAL_DEFAULT_HEIGHT,
    public color: string = '#f00',
    public isFill: boolean = false
  ) {
    super(_startX, _startY, _endX, _endY);
    this.dragComponent = new DragScaleComponent(this, 1);
    this.props.type = ComponentType.SEAL;
  }

  public async render(ctx: CanvasRenderingContext2D) {
    ctx.beginPath();
    ctx.save()
    const radius = (this.endX - this.startX) / 2
    ctx.arc(this.startX + radius, this.startY + radius, radius, 0, Math.PI * 2);
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 2;
    ctx.stroke();
    ctx.restore()
    ctx.drawImage(await loadImage(), this.startX, this.startY, this.width, this.height);
    ctx.closePath();
    this.dragComponent && this.dragComponent.render(ctx)
    this.renderPostion(ctx)
  }

  public isInside(x: number, y: number): boolean {
    const radius = (this.endX - this.startX) / 2
    return Math.hypot(x - (this.startX + radius), y - (this.startY + radius)) <= radius;
  }

  protected doSetWidth(val: number): void {
    this._endX = this._startX + val;
    this._endY = this._startY + val;
  }

  protected doSetHiehgt(val: number): void {
    this._endX = this._startX + val;
    this._endY = this._startY + val;
  }

}
